/*
 * @Author: thl t15945324431@163.com
 * @Date: 2024-01-06 13:53:12
 * @LastEditors: thl t15945324431@163.com
 * @LastEditTime: 2024-02-21 13:50:14
 * @FilePath: \cw_web\gl\src\views\call\serve\serveList\components\table.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { InputNumber } from 'antd';
import React, { useEffect, useState } from 'react';
const App = (props) => {
    const [res, setRes] = useState([]);
    const [titleArr, setTitleArr] = useState([]);
    const [arr, setArr] = useState([]);
    const [row, setRow] = useState([]);
    const [specsFormList, sesSecsFormList] = useState([]);
    const [prevArr, setPrevArr] = useState([]);
    const [rowInput, setRowInput] = useState({});
    const [num, setNum] = useState(0);

    useEffect(() => {
        if (props.arr.length === 0) return
        const prev = JSON.parse(JSON.stringify(arr))
        setPrevArr(prev)
        let propsLength = 0
        let propsChildrenLength = 0
        let arrLength = prevArr.length
        let arrChildrenLength = prevArr.reduce((total, val) => {
            return total += val.children.length
        }, 0)
        let ar = []
        //过滤  规格值为空的
        let arr2 = props.arr.filter(item => {
            if (item.name && item.children) {
                propsChildrenLength += item.children.length
                propsLength += 1
                ar.push(item.name)
                return true
            }
            return false
        })
        if (propsChildrenLength === arrChildrenLength) return
        setTitleArr(ar)
        setArr(arr2)
        if (arr2.length <= 0) return
        // 对数据进行转换
        let res = arrp(arr2)
        setRes(res)
        //添加价格默认值 propsLength !== arrLength ||  || propsChildrenLength != arrChildrenLength
        inputVal(res, ar, propsChildrenLength != arrChildrenLength)
        // 合并单元格
        let row = [];
        let rowspan = res.length;
        // 通过循环，我们获得td所占的rowSpan 所需要的合并的单元格数
        for (let n = 0; n < arr2.length; n++) {
            row[n] = parseInt(rowspan / arr2[n].children.length)
            rowspan = row[n]
        }
        setRow(row)
    }, [props])

    useEffect(() => {
        if (num === 0 && JSON.stringify(props.priceArr) !== "{}") {
            let inputMap = Object.assign(rowInput, props.priceArr)
            specsFormList.map(item => {
                let uuidKey = Object.assign({}, item)
                delete uuidKey["价格"]
                delete uuidKey["预计消耗"]
                let uuid = ""
                Object.keys(uuidKey).map((it, idx) => {
                    uuid += idx > 0 ? ':' : ''
                    uuid += it.split('title:')[1] + ':' + uuidKey[it]
                })
                item['价格'] = inputMap[uuid + ':price']
                item['预计消耗'] = inputMap[uuid + ':expend']
                return item
            })
            setRowInput(inputMap)
            sesSecsFormList(specsFormList)

            props.getData(specsFormList, props.tabIndex)
            setNum(1)
        }
    }, [specsFormList])

    const arrp = (arr) => {
        //编辑原数组格式
        if (arr[0].children) {
            arr = arr.map((item) => {
                return item = item.children
            })
        }
        if (arr.length === 1) {
            //最终合并成一个
            return arr[0];
        } else {	//有两个子数组就合并
            let arrySon = [];
            //将组合放到新数组中
            arr[0].forEach((_, index) => {
                arr[1].forEach((_, index1) => {
                    arrySon.push([].concat(arr[0][index], arr[1][index1]));
                })
            })
            // 新数组并入原数组,去除合并的前两个数组
            arr[0] = arrySon;
            arr.splice(1, 1);
            // 递归
            return arrp(arr);
        }
    }
    const inputVal = (val, title, resetPriceFlag) => {
        let specsFormList = []
        let inputMap = {}
        val.map(item => {
            let uuid = ""
            let specsItem = {}
            if (Array.isArray(item)) {
                item.map((i, idx) => {
                    uuid += idx > 0 ? ':' : '';
                    uuid += title[idx] + ":" + i
                    specsItem['title:' + title[idx]] = i
                })
            } else {
                specsItem[title[0]] = item
                uuid = '宠物分类:' + item
            }
            if (!resetPriceFlag) {
                inputMap[uuid + ':price'] = null
                inputMap[uuid + ':expend'] = null
                specsItem['价格'] = null
                specsItem['预计消耗'] = null
            } else {
                inputMap[uuid + ':price'] = rowInput[uuid + ':price']
                inputMap[uuid + ':expend'] = rowInput[uuid + ':expend']
                specsItem['价格'] = rowInput[uuid + ':price']
                specsItem['预计消耗'] = rowInput[uuid + ':expend']
            }
            specsFormList.push(specsItem)
        })

        sesSecsFormList(specsFormList)
        props.getData(specsFormList, props.tabIndex)
        setRowInput(inputMap)
    }

    // 对表格数据进行渲染
    const tdRow = i => arr.map((_, j) => {
        let td;
        if (i % row[j] === 0 && row[j] > 1) {
            td = <td style={{ textAlign: 'center' }} rowSpan={row[j]} key={j}>{res[i][j] ? res[i][j] : ""}</td>
        } else if (row[j] === 1) {
            res[i] instanceof Array ? td = <td key={j} style={{ textAlign: 'center' }}>{res[i][j]}</td> : td = <td key={j} style={{ textAlign: 'center' }}>{res[i] ? res[i] : "123"}</td>
        }
        return td
    })
    //设置价格
    const setPrice = (params, uuid) => {
        let ua = uuid.split(':')
        specsFormList.map((item, idx) => {
            let flag = Object.keys(item).every((i) => {
                if (!["预计消耗", "价格"].includes(i)) {
                    return ua.includes(i.replace('title:', '')) && ua.includes(item[i])
                }
                return true
            })

            if (flag) specsFormList[idx]["价格"] = params
            return item
        })
        sesSecsFormList([...specsFormList])
        props.getData(specsFormList, props.tabIndex)
        rowInput[uuid + ":price"] = params
        setRowInput({ ...rowInput })
    }
    //设置预计消耗
    const setExpend = (params, uuid) => {
        let ua = uuid.split(':')
        specsFormList.map((item, idx) => {
            let flag = Object.keys(item).every((i) => {
                if (!["预计消耗", "价格"].includes(i)) {
                    return ua.includes(i.replace('title:', '')) && ua.includes(item[i])
                }
                return true
            })
            if (flag) specsFormList[idx]["预计消耗"] = params
            return item
        })
        sesSecsFormList([...specsFormList])
        props.getData(specsFormList, props.tabIndex)
        rowInput[uuid + ":expend"] = params
        setRowInput({ ...rowInput })
    }

    const formatter = (params) => {
        // if (!params) return
        // if (params % 1 == 0) {
        //     params = parseInt(params)
        // }
        return params
    }
    return (
        <div className="table-content">
            <table className="spec-table" border="1">
                <thead>
                    <tr>
                        {
                            arr.map((th, k) => {
                                return <th width="100px" key={k} style={{ textAlign: 'center' }}>{th.name}</th>
                            })
                        }
                        <th style={{ textAlign: 'center', width: "100px" }}>价格（元）</th>
                        <th style={{ textAlign: 'center', width: "100px" }}>预计消耗</th>
                    </tr>
                    {
                        res.map((m, i) => {
                            let uuid = ""
                            if (!["猫猫", "狗狗", "有猫有狗"].includes(m)) {
                                m.map((item, idx) => {
                                    uuid += idx > 0 ? ':' : '';
                                    uuid += titleArr[idx] + ":" + item
                                })
                            } else {
                                uuid = '宠物分类:' + m
                            }
                            return (
                                <tr key={i}>
                                    {
                                        tdRow(i)
                                    }
                                    <td><InputNumber precision={2} formatter={formatter} value={rowInput[uuid + ':price']} onChange={(e) => setPrice(e, uuid)} disabled={props.disabled} /></td>
                                    <td><InputNumber precision={0} value={rowInput[uuid + ':expend']} onChange={(e) => setExpend(e, uuid)} disabled={props.disabled} /></td>
                                </tr>
                            )
                        })
                    }
                </thead>
            </table>
        </div>
    );
};
export default App;